package com.lihui.timer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.lihui.entity.Staff;
import com.lihui.utils.EmailTool;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 生日祝福的任务
 *
 * @author Skyvis-HUI
 * @date 2021/09/28
 */
@Component
@EnableScheduling
@EnableAsync
public class BirthdayWishesTask {

    @Autowired
    private EmailTool emailTool;

    @Scheduled(cron = "${email.run-time}")
    public void task() {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //当前日期月日
        String currentMonthDay = simpleDateFormat.format(new Date()).substring(5, 10);
        // 读取文件
        List<Staff> staffList = new ArrayList<>();
        File file = new File("birthday.txt");
        try {
            InputStreamReader inputReader = new InputStreamReader(new FileInputStream(file));
            BufferedReader bf = new BufferedReader(inputReader);
            // 按行读取字符串
            String str;
            while ((str = bf.readLine()) != null) {
                String tempStr = str.replace(" ", "");
                String[] array = tempStr.split(",");
                if (array.length != 4) {
                    System.out.println("员工资料txt不正确 " + str);
                    continue;
                }
                //出生日期月日
                String bornMonthDay = array[2].substring(5, 10);
                //两个月日相等则是当前生日，添加到集合中，统一发送邮件
                if (currentMonthDay.equals(bornMonthDay)) {
                    staffList.add(new Staff(array[0],array[1]));
                }
            }
            bf.close();
            inputReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("开始发送...");
        long start = System.currentTimeMillis();
        //调用邮件工具类发送邮件
        staffList.forEach(s -> emailTool.sendBirthDayWishes(s.getName(),s.getEmail()));
        System.out.println("发送完成...");
        System.out.println(System.currentTimeMillis() - start);
    }
}

